import { AliSMSService } from './../service/alismsService';
import * as Koa from 'koa';
import { route, RouteOptionsVerify, RouteOptionsBase } from '../common/http';
import * as Jimp from 'jimp';
import { ServiceManager } from '../common/serviceFactory/serviceManager';
import { AuthenService } from '../service/authenService';
import { AliOSS } from '../service/aliossService';
import * as fs from 'fs';
import * as path from 'path';
import { Guid } from '../common';
let pcaCode = require('china-division/dist/pca-code.json');


const authSvr = ServiceManager.Current.GetService<AuthenService>('AuthenService');
const aliOSS = ServiceManager.Current.GetService<AliOSS>('AliOSS');
// const tenSvr = ServiceManager.Current.GetService<TenPayService>('TenPayService');
const aliSMS = ServiceManager.Current.GetService<AliSMSService>('AliSMSService');

const JimpImageWrite = async (image: Jimp, filtPath: string) => {
    return new Promise((resolve, reject) => {
        image.write(filtPath, (err, image) => {
            if (err) {
                reject(err);
            }
            else {
                resolve();
            }
        })
    })
}

class RescoureController {
    @route(new RouteOptionsVerify('POST', '/api/rescoure/file'))
    async uploadFile(ctx: Koa.Context, next) {
        let orgId = ctx.header['orgid'];
        let { mode } = ctx.query;
        let DirName = 'imageStore';
        const file = ctx.request.files.file;
        const reader = fs.createReadStream(file.path);
        let round = Guid.GetGuid();
        DirName += "/" + orgId;
        let hasDir = fs.existsSync(DirName);
        if (!hasDir) {
            fs.mkdirSync(DirName);
        }
        let fileSuffix = getFileSuffix(file.name);
        let fileName = `${round}.${fileSuffix}`;
        let filePath = path.join(__dirname, '../../' + DirName + '/') + fileName;
        // 创建可写流
        const upStream = fs.createWriteStream(filePath);
        // 可读流通过管道写入可写流
        reader.pipe(upStream);

        await saveStreamEnd(upStream);

        let result: any = {};
        if (mode == 'wechat') {
            // 微信支付进件
            // let r: any = await tenSvr.UploadMedia(filePath, file.name);
            // result.wechat = r;
            // let url = await aliOSS.put(`wechatMedia/${storeId}/${r.media_id}.${getFileSuffix(file.name)}`, filePath);
            // fs.unlink(filePath, () => { });
            // result.fileUrl = url;
        }
        else {

            // let url = await aliOSS.put(`imageStore/${storeId}/${round}.${getFileSuffix(file.name)}`, filePath);
            //fs.unlink(filePath, () => { });

            // let url = `imageStore/${orgId}/${round}.${getFileSuffix(file.name)}`;
            let url = DirName + '/' + fileName;
            result.fileUrl = url;
        }

        ctx.response.body = result;

        await next();
    }

    @route(new RouteOptionsBase('get', '/api/industry'))
    async getIndustryConfig(ctx: Koa.Context, next) {
        let result = [
            {
                industry: 'coffee',
                value: '咖啡/奶茶'
            },
            {
                industry: 'hotPot',
                value: '火锅'
            },
            {
                industry: 'westernStyleFood',
                value: '西餐'
            },
            {
                industry: 'chineseFood',
                value: '中餐'
            },
            {
                industry: 'fastFood',
                value: '通用快餐'
            }
        ];

        ctx.response.body = result;

        await next();
    }

    @route(new RouteOptionsVerify('POST', '/api/ali/sms/code/send'))
    async sendVerifyCodeSMS(ctx: Koa.Context, next) {
        let { phone } = ctx.query;
        ctx.response.body = await aliSMS.SendVerifyCodeSMS(phone);
        await next();
    }

    @route(new RouteOptionsBase('GET', '/api/rescoure/china'))
    async getChineseDivisions(ctx: Koa.Context, next) {
        ctx.response.body = pcaCode;
        await next();
    }

    // @route(new RouteOptionsVerify('GET', '/api/ali/sms/code/verify'))
    // async test(ctx: Koa.Context, next) {
    //     let { code, phone } = ctx.query;
    //     ctx.response.body = await aliSMS.VerifcationCode(phone, code);
    //     await next();
    // }
}

const saveStreamEnd = async (upStream) => {
    return new Promise((resovle, reject) => {
        upStream.on('finish', async () => {
            resovle();
        });
    });
}

const getFileSuffix = (fileName: string) => {
    let temp = fileName.split('.');
    if (temp && temp.length > 0) {
        return temp[temp.length - 1];
    }
    else {
        return '';
    }
}